﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;

namespace Mimoza.Plugins.DisplaySettings
{
    public abstract class BaseExecutePlugin : Mimoza.PluginLayer.IExecutePlugin
    {
        #region IExecutePlugin Members

        public string PluginId
        {
            get { return Id; }
        }
        private void StorDataInRegistry( string displayResolution)
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Mimoza", true))
            {
                if (key != null)
                {
                    key.SetValue("DisplayResolution", displayResolution);
                }
            }
        }
        public void Add(Mimoza.ObjectLayer.Policy policy)
        {
            DisplayResolution data = GetData(policy.Data);

            TraceData(data, "Add");

            if (Add(policy, data))
            {
                Mimoza.PluginLayer.PluginResultStore.PutRestartResult();
            }
            StorDataInRegistry(data.DisplayResolutionText);
        }

        public void Remove(Mimoza.ObjectLayer.Policy policy)
        {
            DisplayResolution data = GetData(policy.Data);

            TraceData(data, "Remove");

            Remove(policy, data);
            StorDataInRegistry("800x600x32-60Hz");
        }

        public void Update(Mimoza.ObjectLayer.Policy policy)
        {
            DisplayResolution data = GetData(policy.Data);

            TraceData(data, "Update");

            if (Update(policy, data))
            {
                Mimoza.PluginLayer.PluginResultStore.PutRestartResult();
            }
            StorDataInRegistry(data.DisplayResolutionText);
        }

        #endregion

        public abstract string Id { get; }
        public abstract bool Add(Mimoza.ObjectLayer.Policy policy, DisplayResolution data);
        public abstract bool Remove(Mimoza.ObjectLayer.Policy policy, DisplayResolution data);
        public abstract bool Update(Mimoza.ObjectLayer.Policy policy, DisplayResolution data);

        DisplayResolution GetData(string data)
        {
            return DisplayResolution.Deserialize(data);
        }

        void TraceData(DisplayResolution data, string operation)
        {
            Common.Logger.Log.Trace("Mimoza.Plugins.DisplaySettings Id - '{0}' Operation - '{1}'. Res - '{2}' Color - '{3}' Freq - '{4}'.",
                Id, operation, data.DisplayText, data.ColorDepth.ToString(), data.Freq.ToString());
        }
    }
}
